import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:flutter/material.dart';
import 'package:r_calendar/r_calendar.dart';

import 'default_bottom_sheet.dart';

/// 选择日历
///
/// 返回Date Time
showCalendarBottomSheet(BuildContext context, DateTime selectTime,
    {String title,
    DateTime endDate,
    DateTime startDate,
    bool withinFinancialYear = true}) async {
  DateTime _selectTime = selectTime;
  await showDefaultBottomSheet(
    context,
    child: _CalendarBottomSheet(
      value: selectTime ?? startDate,
      selectCallBack: (data) {
        _selectTime = data;
      },
      startTime: withinFinancialYear && startDate == null
          ? DateTime.tryParse(Config.currentFY.startDate)
          : startDate,
      endTime: withinFinancialYear && endDate == null
          ? DateTime.tryParse(Config.currentFY.endDate)
          : endDate,
    ),
    title: title ?? S.current.date,
    isScrollControlled: true,
  );
  return _selectTime;
}

class _CalendarBottomSheet extends StatefulWidget {
  final DateTime value;
  final ValueChanged<DateTime> selectCallBack;
  final DateTime startTime;
  final DateTime endTime;

  const _CalendarBottomSheet(
      {Key key, this.value, this.selectCallBack, this.startTime, this.endTime})
      : super(key: key);

  @override
  _CalendarBottomSheetState createState() => _CalendarBottomSheetState();
}

class _CalendarBottomSheetState extends State<_CalendarBottomSheet> {
  RCalendarController controller;

  @override
  void initState() {
    super.initState();
    controller = RCalendarController.single(
      mode: RCalendarMode.month,
      selectedDate: widget.value,
      isAutoSelect: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding:
          EdgeInsets.only(left: getDp(50), right: getDp(53), top: getDp(10)),
      height: 375,
      child: RCalendarWidget(
        controller: controller,
        customWidget: NormalCalendarWidget(onSelect: (time) {
          widget.selectCallBack?.call(time);
          Navigator.of(context).pop();
        }),
        firstDate: widget.startTime ?? DateTime(1990, 1, 1),
        lastDate: widget.endTime ?? DateTime(2050, 12, 31),
      ),
    );
  }
}

class NormalCalendarWidget extends RCalendarCustomWidget {
  final ValueChanged<DateTime> onSelect;

  NormalCalendarWidget({this.onSelect});

  @override
  Widget buildDateTime(
      BuildContext context, DateTime time, List<RCalendarType> types) {
    TextStyle childStyle;
    BoxDecoration decoration;

    if (types.contains(RCalendarType.disable) ||
        types.contains(RCalendarType.differentMonth)) {
      childStyle = TextStyle(
        color: aceWhiteGreyColor,
        fontSize: getDp(14),
        letterSpacing: 0.22,
      );
      decoration = BoxDecoration();
    }
    if (types.contains(RCalendarType.normal)) {
      childStyle = TextStyle(
        color: aceBlackColor,
        fontSize: getDp(14),
        letterSpacing: 0.22,
      );
      decoration = BoxDecoration();
    }

    if (types.contains(RCalendarType.today)) {
      childStyle = TextStyle(
        color: Colors.blue,
        fontSize: getDp(14),
        letterSpacing: 0.22,
      );
    }

    if (types.contains(RCalendarType.selected)) {
      childStyle = TextStyle(
        color: Colors.white,
        fontSize: getDp(14),
        letterSpacing: 0.22,
      );
      decoration = BoxDecoration(
        shape: BoxShape.circle,
        color: aceBlueColor,
      );
    }
    return Tooltip(
      message: MaterialLocalizations.of(context).formatFullDate(time),
      child: Container(
          decoration: decoration,
          alignment: Alignment.center,
          child: Text(
            time.day.toString(),
            style: childStyle,
          )),
    );
  }

  @override
  List<Widget> buildWeekListWidget(
      BuildContext context, MaterialLocalizations localizations) {
    return DefaultMaterialLocalizations()
        .narrowWeekdays
        .map(
          (d) => Expanded(
            child: ExcludeSemantics(
              child: Container(
                height: 60,
                alignment: Alignment.center,
                child: Text(
                  d,
                  style: TextStyle(
                      color: aceBlackColor,
                      fontSize: getDp(10),
                      fontWeight: FontWeight.w400),
                ),
              ),
            ),
          ),
        )
        .toList();
  }

  @override
  double get childHeight => getDp(42);

  @override
  FutureOr<bool> clickInterceptor(BuildContext context, DateTime dateTime) {
    onSelect.call(dateTime);
    return true;
  }

  @override
  bool isUnable(BuildContext context, DateTime time, bool isSameMonth) {
    return isSameMonth;
  }

  @override
  Widget buildTopWidget(BuildContext context, RCalendarController controller) {
    final localizations = DefaultMaterialLocalizations();
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        IconButton(
          icon: Icon(Icons.chevron_left),
          onPressed: () {
            controller.previousPage();
          },
        ),
        Text(
          '${localizations.formatMonthYear(controller.displayedMonthDate)}',
          style: TextStyle(
            color: aceBlackColor,
            fontSize: getDp(16),
            fontWeight: FontWeight.w700,
          ),
        ),
        IconButton(
          icon: Icon(Icons.chevron_right),
          onPressed: () {
            controller.nextPage();
          },
        ),
      ],
    );
  }
}
